package com.example.maggie.meizinote.mvp.ui.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.example.maggie.meizinote.app.MApp;
import com.example.maggie.meizinote.app.bean.ClassifyBean;
import com.example.maggie.meizinote.app.bean.note_item;
import com.example.maggie.meizinote.mvp.ui.adapter.HomeMenuAdapter;
import com.example.maggie.meizinote.mvp.ui.adapter.NoteListAdapter;
import com.example.maggie.meizinote.mvp.ui.widget.NoteClassifyDialog;
import com.example.maggie.meizinote.mvp.ui.widget.YesOrNoDialog;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.example.maggie.meizinote.di.component.DaggerHomeComponent;
import com.example.maggie.meizinote.di.module.HomeModule;
import com.example.maggie.meizinote.mvp.contract.HomeContract;
import com.example.maggie.meizinote.mvp.presenter.HomePresenter;

import com.example.maggie.meizinote.R;
import com.liaoinstan.springview.container.DefaultHeader;
import com.liaoinstan.springview.widget.SpringView;


import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.OnClick;

import static com.jess.arms.utils.Preconditions.checkNotNull;


public class HomeActivity extends BaseActivity<HomePresenter> implements HomeContract.View {
    @BindView(R.id.recycler_view)
    RecyclerView recycler_view;
    RecyclerView recycler_view_classify;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.drawer_layout)
    DrawerLayout drawer;
    @BindView(R.id.nav_view)
    NavigationView navigationView;
    @Inject
    NoteListAdapter adapter;
    @Inject
    HomeMenuAdapter adapterClassify;
    @BindView(R.id.springview)
    SpringView springView;
    TextView email;

    @OnClick({R.id.fab, R.id.process, R.id.search})
    void onClick(View view) {
        switch (view.getId()) {
            case R.id.fab:
                launchActivity(new Intent(this, NoteEditActivity.class)
                        .putExtra("classifyId", mPresenter.classifyId)
                );
                break;
            case R.id.process:
                process();
                break;
            case R.id.search:
                launchActivity(new Intent(this, SearchActivity.class)
                        .putExtra("classifyId", mPresenter.classifyId)
                );
                break;
        }
    }

    private void process() {
        mPresenter.getClassifyData();
        mPresenter.getData();
    }

    @Override
    protected void onResume() {
        super.onResume();
        process();
        dayOrNight();
    }

    @Override
    public void setupActivityComponent(AppComponent appComponent) {
        DaggerHomeComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .homeModule(new HomeModule(this))
                .build()
                .inject(this);
    }

    @Override
    public int initView(Bundle savedInstanceState) {
        return R.layout.drawable_layout; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }


    @Override
    public void initData(Bundle savedInstanceState) {
        setTitle("笔记列表");
        String id = MApp.getUserId();
        if (id == null && id.trim().isEmpty()) {
            //未登录状态直接进入登录页
            mPresenter.toLogin();
        }
        setSupportActionBar(toolbar);
        email = navigationView.getHeaderView(0).findViewById(R.id.email);
        recycler_view_classify = navigationView.getHeaderView(0).findViewById(R.id.recycler_view);
        navigationView.getHeaderView(0).findViewById(R.id.add_note_classify).setOnClickListener(mPresenter);
        navigationView.getHeaderView(0).findViewById(R.id.logout).setOnClickListener(mPresenter);
        navigationView.getHeaderView(0).findViewById(R.id.day_or_night).setOnClickListener(mPresenter);

        email.setText(MApp.getEmail());

        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();

        setAdapter(recycler_view, adapter);
        setAdapter(recycler_view_classify, adapterClassify);

        springView.setType(SpringView.Type.FOLLOW);

        springView.setListener(new SpringView.OnFreshListener() {
            @Override
            public void onRefresh() {
                process();
            }

            @Override
            public void onLoadmore() {
            }
        });
        springView.setHeader(new DefaultHeader(this));   //参数为：logo图片资源，是否显示文字
    }

    private void setAdapter(RecyclerView recycler_view, BaseQuickAdapter adapter) {
        recycler_view.setLayoutManager(new LinearLayoutManager(getApplicationContext()));// 布局管理器
        recycler_view.setAdapter(adapter);
        recycler_view.setItemAnimator(new DefaultItemAnimator());
        adapter.setOnItemChildClickListener(mPresenter);
        adapter.setOnItemClickListener(mPresenter);
        adapter.setOnItemLongClickListener(mPresenter);
        adapter.bindToRecyclerView(recycler_view);
        adapter.setEmptyView(R.layout.view_empty);
    }

    @Override
    public void onBackPressed() {
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()) {
            case android.R.id.home:
                drawer.openDrawer(GravityCompat.START);
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.snackbarText(message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }


    @Override
    public void dayOrNight() {
        if (MApp.isNight) {
            drawer.setBackgroundColor(getResources().getColor(R.color.night_bg_color));
            toolbar.setBackgroundColor(getResources().getColor(R.color.night_toolbar_color));
            navigationView.setBackgroundColor(getResources().getColor(R.color.night_bg_color));
        } else {
            drawer.setBackgroundColor(getResources().getColor(R.color.day_bg_color));
            toolbar.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
            navigationView.setBackgroundColor(getResources().getColor(R.color.day_bg_color));
        }
        adapter.notifyDataSetChanged();
        adapterClassify.notifyDataSetChanged();
        setColor();
    }

    public void setColor() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            if (MApp.isNight)
                window.setStatusBarColor(getResources().getColor(R.color.night_toolbar_color));
            else
                window.setStatusBarColor(getResources().getColor(R.color.colorPrimary));
        }
    }

    @Override
    public void addData(List<note_item> object) {
        drawer.closeDrawer(GravityCompat.START);
        adapter.setNewData(object);
        springView.onFinishFreshAndLoad();
    }

    @Override
    public void showClassifyDelectDialog(ClassifyBean item) {
        if (this != null)
            new YesOrNoDialog.Builder(this)
                    .setTitle("删除目录")
                    .setMessage("是否删除目录\"" + item.getTitle() + "\" ?")
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            mPresenter.delectClassify(item);
                            dialogInterface.dismiss();
                        }
                    })
                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            dialogInterface.dismiss();
                        }
                    })
                    .create().show();
    }

    @Override
    public void showClassifyEditDialog(String name, String id) {
        if (this != null)
            new NoteClassifyDialog.Builder(this)
                    .setClassify_name(name)
                    .setId(id)
                    .setTitle("请输入笔记名:")
                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            dialogInterface.dismiss();
                        }
                    })
                    .setPositiveButton("确定", mPresenter)
                    .create()
                    .show();
    }

    @Override
    public void setClassifyData(List<ClassifyBean> object) {
        ClassifyBean all = new ClassifyBean();
        all.setTitle("全部");
        object.add(0, all);
        adapterClassify.setNewData(object);
        adapter.setClassifyData(object);
    }
}
